package com.xc.quickstart.common.interceptor;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.Instant;

/**
 * @author yinyansheng
 */
@Slf4j
public class LogProxyInvocationHandler implements InvocationHandler {

    private Object target;

    public LogProxyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Instant begin = Instant.now();

        log.info("[LogCglibInterceptor]调用开始 method:{},args:{}"
                , method.getDeclaringClass().getName() + "." + method.getName()
                , JSON.toJSONString(args));

        Object result = method.invoke(target, args);

        log.info("[LogControllerAspect]调用结束 method:{},args:{},result:{},cost:{},speed:{}"
                , method.getDeclaringClass().getName() + "." + method.getName()
                , JSON.toJSONString(args)
                , JSON.toJSONString(result)
                , Duration.between(begin, Instant.now()).toMillis()
                , Duration.between(begin, Instant.now()).toMillis() > 500 ? "<<slow>>" : "<<fast>>");

        return result;
    }
}
